<template>
  <div>
    <!-- imediatechek 默认为true 是否在页面初始化立即执行滚动位置检查 -->
    <van-list
      v-model="loading"
      @load="onLoad"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
    >
      <commentItem
        v-for="item in comItem"
        :key="item.com_id"
        :comItem="item"
        @replyFn="replyFn"
      ></commentItem>
    </van-list>
  </div>
</template>

<script>
import commentItem from "./commentItem.vue";
import { getCommentListApi } from "@/api/comment";
export default {
  data() {
    return {
      comItem: [],
      loading: false,
      finished: false,
      offset: "",
    };
  },
  props: {
    artId: {
      type: [Number, String],
    },
    newCommentObj: Object,
    type: [String, Number],
  },
  components: {
    commentItem,
  },
  created() {
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        let obj = {
          type: this.type,
          source: this.artId,
          offset: this.offset,
          limit: 10,
        };
        let { data } = await getCommentListApi(obj);
        if (data.data.results.length == 0) {
          this.finished = true;
        } else {
          this.offset = data.data.last_id;
          this.comItem = [...this.comItem, ...data.data.results];
          this.loading = false;

          //向父组件传递评论总数
          this.$emit("totalCountFn", data.data.total_count);
        }
      } catch (error) {
        console.log(error);
      }
    },
    replyFn(item) {
      this.$emit("replyFn", item);
    },
  },
  watch: {
    newCommentObj: {
      deep: true,
      handler(newVal) {
        //将添加的最新的评论 插入列表的头部
        let bool = this.commentItem.find((item) => {
          return item.com_id == newVal.com_id;
        });
        //存在的数据不插入 只插入不存在的数据
        if (!bool) {
          this.comItem.unshift(newVal);
        }
      },
    },
  },
};
</script>

<style></style>
